﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DeviceCommon;
using MsgPack.Serialization;
using System.IO;
using SuperSocket.ProtoBase;
using LogLib;

namespace DeviceControlClient
{
    public class ResponsePackageInfo : IPackageInfo
    {
        public string Key
        {
            get 
            {
                return ActionState.ToString();
            }
        }

        public ResponsePackageInfo(DeviceActionState action, byte[] bodyBuffer)
        {
            ActionState = action;
            BodyData = bodyBuffer;
        }

        /// <summary>
        /// 服务器返回的字节数据头部
        /// </summary>
        private DeviceActionState ActionState = DeviceActionState.TestOK;

        /// <summary>
        /// 服务器返回的字节数据
        /// </summary>
        public byte[] BodyData { get; set; }

        /// <summary>
        /// 服务器返回的字符串数据
        /// </summary>
        public ResponseMsgPackge Packge
        {
            get
            {
                if (BodyData == null || BodyData.Length == 0)
                {
                    return null;
                }
                Log.WriteAsync($"Receive BodyData data: Length={Key}, Length={BodyData.Length}");
                if (Key == "StartOK" && BodyData.Length == 36)
                {
                    return null;
                }              
                var serializer = SerializationContext.Default.GetSerializer<ResponseMsgPackge>();
                try
                {
                    using (var stream = new MemoryStream(BodyData, 0, BodyData.Length))
                    {
                        ResponseMsgPackge pack = serializer.Unpack(stream) as ResponseMsgPackge;
                        if(pack != null)
                        {
                            Log.WriteAsync($"Receive socket data: Key={pack}");
                        }
                        return pack;
                    }
                }
                catch (Exception ex)
                {
                    Log.WriteAsync($"key={Key}");
                    Log.WriteException(ex.ToString());
                    return null;
                }              
            }
        }
    }
}
